package org.clockworkmages.games.anno1186.situations.gameoptions.options;

import java.io.File;
import java.io.FileReader;
import java.io.Reader;

import org.clockworkmages.games.anno1186.GameBeansContext;
import org.clockworkmages.games.anno1186.GameCharacterService;
import org.clockworkmages.games.anno1186.GameDataService;
import org.clockworkmages.games.anno1186.GameGuiService;
import org.clockworkmages.games.anno1186.GameState;
import org.clockworkmages.games.anno1186.GameStateService;
import org.clockworkmages.games.anno1186.dao.SerializationUtil;
import org.clockworkmages.games.anno1186.gui.GameUiUtil;
import org.clockworkmages.games.anno1186.model.option.Option;

public class SelectLoadSlotOption
		extends Option {

	private GameStateService gameStateService;
	private GameGuiService gameGuiService;
	private GameCharacterService gameCharacterService;
	private GameDataService gameDataService;
	private String fileName;

	public SelectLoadSlotOption(int index, String fileName) {
		gameDataService = GameBeansContext.getBean(GameDataService.class);
		gameStateService = GameBeansContext.getBean(GameStateService.class);
		gameGuiService = GameBeansContext.getBean(GameGuiService.class);
		gameCharacterService = GameBeansContext
				.getBean(GameCharacterService.class);
		setLabel("Game slot " + index);
		setTextAfter("Game loaded succesfully.");
		this.fileName = fileName;
	}

	@Override
	public void select() {
		try {
			File saveFile = new File("./" + fileName);
			Reader reader = new FileReader(saveFile);

			GameState gameStateFromFile = SerializationUtil.deserialize(reader,
					GameState.class);

			gameStateFromFile.getSituationStack().clear();

			gameStateService.setGameState(gameStateFromFile);
			gameCharacterService.refreshStats(gameStateFromFile.getCharacter());
		} catch (Exception e) {
			GameUiUtil.logError(e);
			throw new RuntimeException(e);
		}
		super.select();
	}
}
